# Usage: territories.tcl variant.map

package require Iexpect

set parsing 0
set skipped {}
proc parse {} {
	global parsing skipped
	if {!$parsing} {
		set parsing 1
		if {[string length $skipped]} {puts "Not: $skipped"}
		set skipped {}
	}
}
proc skip {line} {
	global parsing skipped
	if {$parsing} {
		set parsing 0
		if {[string length $line]} {puts "Nor: $line"}
	} else {
		set skipped $line
	}
}

set types {COAST LAND WATER GREEN BEACH SHUT PORT}
array set places {}
foreach type $types {
	set places($type) []
}

if {[llength $argv] != 1} {
	puts "Usage: [file tail [info script]] variant.map"
} elseif {![file exists [lindex $argv 0]]} {
	puts "File does not exist in [pwd]: [lindex $argv 0]"
} else {
	set I [iexpect::Expect #auto -white -file [lindex $argv 0] -encoding "iso8859-1"]
	$I expect line "^COAST (\\w+)(/\\w+)?" {
		parse
		if {[string length [$I get match 2]]} {
			lappend places(BEACH) "[$I get match 1][$I get match 2]"
		} elseif {[string tolower [$I get match 1]] == [$I get match 1]} {
			lappend places(GREEN) [string toupper [$I get match 1]]
		} else {
			lappend places(COAST) [$I get match 1]
		}
		$I continue
	} "^(LAND|WATER|PORT|SHUT) (\\w+)" {
		parse
		lappend places([$I get match 1]) [$I get match 2]
		$I continue
	} default {
		skip [$I get output]
		$I continue
	}
	itcl::delete object $I
	
	foreach type $types {
		if {[llength $places($type)]} {
			puts "$type: $places($type)"
		}
	}
}